package com.zzy.mccjt.model;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.zzy.mccjt.constant.RequestConstant;
import lombok.Data;
import org.slf4j.MDC;

import java.util.Optional;

/**
 * @program: mccjt-cloud
 * @description:
 * @author: zhouyang.zheng
 * @create: 2022-08-02 17:55
 **/
public class CurrentTenant {

    @Data
    public static class TenantInfo {
        private Long id;
        private String code;

        public TenantInfo(Long id, String code) {
            this.setId(id);
            this.setCode(code);
        }
    }

    private static final TransmittableThreadLocal<TenantInfo> CURRENT = new TransmittableThreadLocal<>();

    public static void set(Long id, String code) {
        set(new TenantInfo(id, code));
    }

    public static void set(TenantInfo info) {
        CURRENT.set(info);
        MDC.put(RequestConstant.TENANT_ID, String.valueOf(info.getId()));
    }

    public static TenantInfo getInfo() {
        return CURRENT.get();
    }

    public static Long getId() {
        return Optional.ofNullable(getInfo())
                .map(TenantInfo::getId)
                .orElse(null);
    }

    public static String getCode() {
        return Optional.ofNullable(getInfo())
                .map(TenantInfo::getCode)
                .orElse(null);
    }

    public static boolean exists() {
        return getInfo() != null && getInfo().getId() != null && getInfo().getCode() != null;
    }

    public static boolean existsId() {
        return getInfo() != null && getInfo().getId() != null;
    }

    public static boolean existsCode() {
        return getInfo() != null && getInfo().getCode() != null;
    }

    public static void clear() {
        CURRENT.remove();
        MDC.remove(RequestConstant.TENANT_ID);
    }
}
